/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 PostActionListenersContainer.hpp. Created on: 24.08.2009 13:19:19
 */

#ifndef POSTACTIONLISTENERSCONTAINER_HPP_
#define POSTACTIONLISTENERSCONTAINER_HPP_

#include "cpputils/CppUtils.hpp"

namespace cpputils {

namespace utils {

template<typename T>
class PostActionListenersContainer {
public:
	enum PostActionType {
		NONE, ADD, REMOVE
	};

	struct PostActionQueueItem {
		T* m_poListener;
		PostActionType m_nActionType;
		inline PostActionQueueItem(): m_poListener(NULL), m_nActionType(NONE) { };
		inline PostActionQueueItem(T* poListener, PostActionType nActionType): m_poListener(poListener), m_nActionType(nActionType) {}

		inline bool isActionToAdd() { return m_nActionType == ADD; }
		inline bool isActionToRemove() { return m_nActionType == REMOVE; }
		inline T* getListener() { return m_poListener; }
	};

	typedef std::list<PostActionQueueItem> PostActionQueue;

	struct ScopeMonitor {
		inline ScopeMonitor(PostActionListenersContainer<T>& oContainer, bool bInitialActivate=true): m_oContainer(oContainer) {
			if(bInitialActivate)
				m_oContainer.activate();
		}

		inline ~ScopeMonitor() {
			m_oContainer.reset();
		}

	private:
		PostActionListenersContainer<T>& m_oContainer;
	};

public:
	inline PostActionListenersContainer(): m_bIsActivated(false) {};
	inline ~PostActionListenersContainer() {};

	inline const PostActionQueue& getPostActionQueue() { return m_aPostActionQueue; };
	inline void putListenerToAdd(T* listener) { m_aPostActionQueue.push_back( PostActionQueueItem(listener, ADD) );  };
	inline void putListenerToRemove(T* listener) { m_aPostActionQueue.push_back( PostActionQueueItem(listener, REMOVE) );  };
	inline void activate() { m_bIsActivated=true; };
	inline void deactivate() { m_bIsActivated=false; };
	inline void reset() { m_bIsActivated=false; m_aPostActionQueue.clear(); };
	inline bool isActivated() { return m_bIsActivated; };

private:
	bool m_bIsActivated;
	PostActionQueue m_aPostActionQueue;

};


}

}

#endif /* POSTACTIONLISTENERSCONTAINER_HPP_ */
